package utils.db.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pojo.Device;
import pojo.EDeviceState;
import utils.db.api.IDeviceFetcher;
import utils.db.mapper.IMapper;
import utils.db.mapper.Mapper;

public class DeviceFetcher extends DBOperation implements IDeviceFetcher {
	private static Logger logger = LoggerFactory.getLogger(DeviceFetcher.class);
	private Device device;
	private IMapper mapper;

	public DeviceFetcher() {
		super();
		mapper = new Mapper();

	}

	public Device getDevice(Integer id) {
		try {
			pstmt = getConnector().prepareStatement(GET_DEVICE_BY_ID);
			pstmt.setInt(1, id);
			rs = pstmt.executeQuery();
			if (rs.next())
				device = mapper.deviceMapp(rs);
			pstmt.close();
		} catch (SQLException e) {
			logger.error("Error during fetch user");
		}
		logger.info("Added user " + device.toString());
		return device;
	}

	public List<Device> getDevices() {
		List<Device> devices = new ArrayList<Device>();
		try {
			pstmt = getConnector().prepareStatement(GET_ALL_DEVICES);
			rs = pstmt.executeQuery();
			devices = mapper.devicesMapp(rs);
			pstmt.close();
		} catch (SQLException e) {
			logger.error("Error during fetch user");
		}
		return devices;
	}

	@Override
	public List<Device> getDevicesByIdServiceman(int id) {
		List<Device> devices = getManyDevice(id, GET_DEVICES_BY_ID_SERVICEMAN );
		return devices;
	}
	
	@Override
	public List<Device> getDeviceByIdClient(int id) {
		List<Device> devices = getManyDevice(id, GET_DEVICES_BY_ID_CLIENT);
		return devices;
	}
	
	@Override
	public List<Device> getDeviceByState(String state) {
		List<Device> devices = getManyDevice(state, GET_DEVICE_BY_STATE);
		return devices;
	}

	private List<Device> getManyDevice(int id, String query) {
		List<Device> devices = new ArrayList<Device>();
		try {
			pstmt = getConnector().prepareStatement(
					query);
			pstmt.setString(1, String.valueOf(id));
			rs = pstmt.executeQuery();
			devices = mapper.devicesMapp(rs);
			pstmt.close();
		} catch (SQLException e) {
			logger.error("Error during fetch devices");
		}
		return devices;
	}
	
	private List<Device> getManyDevice(String id, String query) {
		List<Device> devices = new ArrayList<Device>();
		try {
			pstmt = getConnector().prepareStatement(
					query);
			pstmt.setString(1, String.valueOf(id));
			rs = pstmt.executeQuery();
			devices = mapper.devicesMapp(rs);
			pstmt.close();
		} catch (SQLException e) {
			logger.error("Error during fetch devices");
		}
		return devices;
	}
	
	public static void main(String[] args) {
		DeviceFetcher dfetcher = new DeviceFetcher();
		System.out.println(dfetcher.getDeviceByState(EDeviceState.INPROGRESS.name()));
	}

	

}
